<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <title>天气预报系统</title>
  <style>
    body {
      background: linear-gradient(to right, #83a4d4, #b6fbff);
      font-family: 'Segoe UI', sans-serif;
      margin: 0;
      padding: 0;
      display: flex;
      flex-direction: column;
      align-items: center;
      min-height: 100vh;
    }
    h1 {
      margin-top: 40px;
      color: #333;
    }
    .weather-container {
      background: white;
      padding: 30px;
      border-radius: 15px;
      box-shadow: 0 5px 15px rgba(0,0,0,0.2);
      margin-top: 20px;
      width: 90%;
      max-width: 600px;
      text-align: center;
    }
    select, input, button {
      padding: 10px;
      margin: 10px 5px;
      font-size: 16px;
      border-radius: 8px;
      border: 1px solid #ccc;
    }
    button {
      background-color: #4CAF50;
      color: white;
      cursor: pointer;
    }
    button:hover {
      background-color: #45a049;
    }
    .result {
      margin-top: 20px;
      font-size: 16px;
      color: #333;
    }
    .forecast {
      margin-top: 20px;
      text-align: left;
    }
    .forecast-day {
      margin: 10px 0;
      padding: 10px;
      border-bottom: 1px solid #ccc;
    }
    .error {
      color: red;
    }
  </style>
</head>
<body>

  <h1>🌦️ 实时 + 7天天气预报</h1>

  <div class="weather-container">
    <select id="citySelect" title="选择城市"></select>
      <option value="">选择城市</option>
      <option value="Beijing">北京</option>
      <option value="Shanghai">上海</option>
      <option value="Guangzhou">广州</option>
      <option value="Shenzhen">深圳</option>
      <option value="Tokyo">东京</option>
      <option value="New York">纽约</option>
    </select>

    <input type="text" id="cityInput" placeholder="或手动输入城市名（如 Hangzhou）">
    <button onclick="loadWeather()">查询天气</button>

    <div class="result" id="weatherResult"></div>
    <div class="forecast" id="forecast"></div>
  </div>

  <script>
    const apiKey = "YOUR_API_KEY_HERE"; // ← 替换为你的 OpenWeatherMap API Key

    async function loadWeather() {
      const inputCity = document.getElementById("cityInput").value.trim();
      const selectedCity = document.getElementById("citySelect").value;
      const city = inputCity || selectedCity;
      if (!city) {
        alert("请选择或输入城市名！");
        return;
      }

      const weatherBox = document.getElementById("weatherResult");
      const forecastBox = document.getElementById("forecast");
      weatherBox.innerHTML = "🔍 正在加载天气数据...";
      forecastBox.innerHTML = "";

      try {
        // 第一步：通过地理编码获取经纬度
        const geoRes = await fetch(`https://api.openweathermap.org/geo/1.0/direct?q=${city}&limit=1&appid=${apiKey}`);
        const geoData = await geoRes.json();
        if (!geoData.length) throw new Error("城市未找到");

        const { lat, lon, name } = geoData[0];

        // 第二步：通过经纬度获取天气数据（One Call API）
        const weatherRes = await fetch(`https://api.openweathermap.org/data/2.5/onecall?lat=${lat}&lon=${lon}&appid=${apiKey}&units=metric&lang=zh_cn`);
        const weatherData = await weatherRes.json();

        const current = weatherData.current;
        const daily = weatherData.daily;

        // 显示当前天气
        weatherBox.innerHTML = `
          <h2>${name} 当前天气</h2>
          ☁ 天气：${current.weather[0].description}<br>
          🌡 温度：${current.temp}°C<br>
          💧 湿度：${current.humidity}%<br>
          💨 风速：${current.wind_speed} m/s
        `;

        // 显示未来7天天气
        forecastBox.innerHTML = `<h3>📅 未来7天天气预报</h3>`;
        for (let i = 1; i <= 7; i++) {
          const day = daily[i];
          const date = new Date(day.dt * 1000);
          const dateStr = date.toLocaleDateString("zh-CN", { weekday: 'long', month: 'numeric', day: 'numeric' });

          forecastBox.innerHTML += `
            <div class="forecast-day">
              <strong>${dateStr}</strong><br>
              ☁ 天气：${day.weather[0].description}<br>
              🌡 温度：${day.temp.min}°C ~ ${day.temp.max}°C<br>
              💧 湿度：${day.humidity}%<br>
              💨 风速：${day.wind_speed} m/s
            </div>
          `;
        }

      } catch (err) {
        weatherBox.innerHTML = `<p class="error">❌ 错误：${err.message}</p>`;
      }
    }
  </script>

</body>
</html>
